<template>
  <div class="page-container">
    <h2 style="margin-bottom: 20px;">用户管理</h2>
    
    <!-- 搜索和操作区域 -->
    <div class="search-actions-bar" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
      <t-space>
        <t-button theme="primary" @click="showCreateDialog = true">
          <template #icon><t-icon name="add" /></template>
          新增用户
        </t-button>
        <t-button variant="outline" @click="handleExport">
          <template #icon><t-icon name="download" /></template>
          导出数据
        </t-button>
        <t-button variant="outline" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
          <template #icon><t-icon name="delete" /></template>
          批量删除
        </t-button>
      </t-space>
      
      <t-space>
        <t-input
          v-model="searchText"
          placeholder="请输入用户名或邮箱搜索"
          clearable
          @enter="handleQuickSearch"
          @clear="handleQuickSearch"
          style="width: 300px;"
        >
          <template #suffix-icon>
            <t-icon name="search" />
          </template>
        </t-input>
        <t-button variant="outline" @click="showAdvancedSearch = true">
          <template #icon><t-icon name="search" /></template>
          高级查询
        </t-button>
      </t-space>
    </div>
    
    <t-table
      :data="userList"
      :columns="columns"
      :loading="loading"
      row-key="id"
      :pagination="false"
    >
      <template #status="{ row }">
        <t-tag :theme="row.status === 1 ? 'success' : 'danger'" variant="light">
          {{ row.status === 1 ? '正常' : '禁用' }}
        </t-tag>
      </template>
      
      <template #roles="{ row }">
        <t-space>
          <t-tag v-for="role in row.roles" :key="role.id" theme="primary" variant="light">
            {{ role.name }}
          </t-tag>
        </t-space>
      </template>
      
      <template #op="{ row }">
        <t-space>
          <t-button variant="text" theme="primary" @click="handleEdit(row)">编辑</t-button>
          <t-button variant="text" theme="primary" @click="handleChangePassword(row)">改密</t-button>
          <t-popconfirm content="确定删除该用户吗？" @confirm="handleDelete(row.id)">
            <t-button variant="text" theme="danger">删除</t-button>
          </t-popconfirm>
        </t-space>
      </template>
    </t-table>
    
    <!-- TDesign分页组件 -->
    <div style="margin-top: 16px; display: flex; justify-content: flex-end;">
      <t-pagination
        v-model:current="pagination.current"
        v-model:pageSize="pagination.pageSize"
        :total="pagination.total"
        :page-size-options="pagination.pageSizeOptions"
        show-jumper
        show-page-size
        @change="handlePageChange"
      />
    </div>
    
    <!-- 新增/编辑对话框 -->
    <t-dialog
      v-model:visible="showCreateDialog"
      :header="editUser ? '编辑用户' : '新增用户'"
      width="600px"
      @confirm="handleSubmit"
    >
      <t-form ref="formRef" :data="formData" :rules="rules" label-width="80px">
        <t-form-item label="用户名" name="username">
          <t-input v-model="formData.username" :disabled="!!editUser" placeholder="请输入用户名" />
        </t-form-item>
        <t-form-item v-if="!editUser" label="密码" name="password">
          <t-input v-model="formData.password" type="password" placeholder="请输入密码" />
        </t-form-item>
        <t-form-item label="邮箱" name="email">
          <t-input v-model="formData.email" placeholder="请输入邮箱" />
        </t-form-item>
        <t-form-item label="手机号" name="phone">
          <t-input v-model="formData.phone" placeholder="请输入手机号" />
        </t-form-item>
        <t-form-item label="状态" name="status">
          <t-radio-group v-model="formData.status">
            <t-radio value="1">正常</t-radio>
            <t-radio value="0">禁用</t-radio>
          </t-radio-group>
        </t-form-item>
        <t-form-item label="角色" name="role_ids">
          <t-select v-model="formData.role_ids" multiple placeholder="请选择角色">
            <t-option v-for="role in roleOptions" :key="role.id" :value="role.id" :label="role.name" />
          </t-select>
        </t-form-item>
      </t-form>
    </t-dialog>
    
    <!-- 修改密码对话框 -->
    <t-dialog
      v-model:visible="showPasswordDialog"
      header="修改密码"
      width="400px"
      @confirm="handlePasswordSubmit"
    >
      <t-form ref="passwordFormRef" :data="passwordForm" :rules="passwordRules" label-width="80px">
        <t-form-item label="新密码" name="newPassword">
          <t-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" />
        </t-form-item>
      </t-form>
    </t-dialog>

    <!-- 高级查询对话框 -->
    <t-dialog
      v-model:visible="showAdvancedSearch"
      header="高级查询"
      width="800px"
      :confirm-btn="{
        content: '查询',
        theme: 'primary'
      }"
      :cancel-btn="{
        content: '重置',
        theme: 'default',
        variant: 'base'
      }"
      @confirm="handleAdvancedSearch"
      @cancel="handleResetAdvancedSearch"
    >
      <t-form :data="searchForm" label-width="100px" :colon="true">
        <div style="display: grid; grid-template-columns: 1fr 1fr;">
          <t-form-item label="用户名">
            <t-input v-model="searchForm.username" placeholder="请输入用户名" />
          </t-form-item>
          
          <t-form-item label="邮箱">
            <t-input v-model="searchForm.email" placeholder="请输入邮箱" />
          </t-form-item>
          
          <t-form-item label="状态">
            <t-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <t-option value="1" label="正常" />
              <t-option value="0" label="禁用" />
            </t-select>
          </t-form-item>
          
          <t-form-item label="角色">
            <t-select v-model="searchForm.role_id" placeholder="请选择角色" clearable>
              <t-option v-for="role in roleOptions" :key="role.id" :value="role.id" :label="role.name" />
            </t-select>
          </t-form-item>
          
          <t-form-item label="手机号">
            <t-input v-model="searchForm.phone" placeholder="请输入手机号" />
          </t-form-item>
          
          <t-form-item label="创建时间" style="grid-column: span 2;">
            <t-date-range-picker v-model="searchForm.createTime" style="width: 100%;" />
          </t-form-item>
        </div>
      </t-form>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { userAPI } from '@/api/user'
import { roleAPI } from '@/api/role'
import type { User, Role } from '@/types'

const loading = ref(false)
const userList = ref<User[]>([])
const roleOptions = ref<Role[]>([])
const showCreateDialog = ref(false)
const showPasswordDialog = ref(false)
const editUser = ref<User | null>(null)
const currentPasswordUser = ref<User | null>(null)

const showAdvancedSearch = ref(false)
const searchText = ref('')
const selectedRows = ref<User[]>([])

const searchForm = reactive({
  username: '',
  email: '',
  status: '',
  role_id: '',
  phone: '',
  createTime: []
})

const formData = reactive({
  username: '',
  password: '',
  email: '',
  phone: '',
  status: '1',
  role_ids: [] as number[]
})

const passwordForm = reactive({
  newPassword: ''
})

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  pageSizeOptions: [10, 20, 50, 100]
})

const columns = [
  { colKey: 'id', title: 'ID', width: 80 },
  { colKey: 'username', title: '用户名' },
  { colKey: 'email', title: '邮箱' },
  { colKey: 'phone', title: '手机号' },
  { colKey: 'status', title: '状态' },
  { colKey: 'roles', title: '角色' },
  { 
    colKey: 'created_at', 
    title: '创建时间',
    cell: (h: any, { row }: any) => {
      if (!row.created_at) return '-'
      const date = new Date(row.created_at)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        hour12: false
      }).replace(/\//g, '-')
    }
  },
  { colKey: 'op', title: '操作', width: 200, fixed: 'right' }
]

const rules = {
  username: [{ required: true, message: '请输入用户名' }],
  email: [{ required: true, message: '请输入邮箱' }, { type: 'email', message: '邮箱格式不正确' }]
}

const passwordRules = {
  newPassword: [{ required: true, message: '请输入新密码' }]
}

const loadUsers = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize
    }
    
    // 处理快速搜索
    if (searchText.value) {
      params.keyword = searchText.value
    } else {
      // 处理高级搜索条件
      Object.assign(params, searchForm)
      // 过滤空值
      Object.keys(params).forEach(key => {
        if (params[key] === '' || params[key] === null || params[key] === undefined) {
          delete params[key]
        }
      })
    }
    
    const response = await userAPI.getUsers(params)
    console.log('API Response:', response)
    userList.value = response.data || []
    pagination.total = response.total || 0
    console.log('Total value:', pagination.total)
  } catch (error) {
    MessagePlugin.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const loadRoles = async () => {
  try {
    const response = await roleAPI.getRoles({ page: 1, pageSize: 100 })
    roleOptions.value = response.data
  } catch (error) {
    MessagePlugin.error('获取角色列表失败')
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadUsers()
}

const handleQuickSearch = () => {
  pagination.current = 1
  loadUsers()
}

const handleAdvancedSearch = () => {
  showAdvancedSearch.value = false
  pagination.current = 1
  loadUsers()
}

const handleResetAdvancedSearch = () => {
  Object.assign(searchForm, {
    username: '',
    email: '',
    status: '',
    role_id: '',
    phone: '',
    createTime: []
  })
}

const handleReset = () => {
  searchText.value = ''
  Object.assign(searchForm, {
    username: '',
    email: '',
    status: '',
    role_id: '',
    phone: '',
    createTime: []
  })
  pagination.current = 1
  loadUsers()
}

const handleExport = () => {
  MessagePlugin.info('导出功能开发中')
}

const handleBatchDelete = () => {
  MessagePlugin.info('批量删除功能开发中')
}

const handlePageChange = (pageInfo: any) => {
  pagination.current = pageInfo.current
  pagination.pageSize = pageInfo.pageSize
  loadUsers()
}

const handleEdit = (user: User) => {
  editUser.value = user
  Object.assign(formData, {
    username: user.username,
    email: user.email,
    phone: user.phone,
    status: user.status.toString(),
    role_ids: user.roles.map(role => role.id)
  })
  showCreateDialog.value = true
}

const handleChangePassword = (user: User) => {
  currentPasswordUser.value = user
  passwordForm.newPassword = ''
  showPasswordDialog.value = true
}

const handleDelete = async (id: number) => {
  try {
    await userAPI.deleteUser(id)
    MessagePlugin.success('删除成功')
    loadUsers()
  } catch (error) {
    MessagePlugin.error('删除失败')
  }
}

const handleSubmit = async () => {
  try {
    if (editUser.value) {
      await userAPI.updateUser(editUser.value.id, {
        email: formData.email,
        phone: formData.phone,
        status: parseInt(formData.status),
        role_ids: formData.role_ids
      })
      MessagePlugin.success('更新成功')
    } else {
      await userAPI.createUser({
        username: formData.username,
        password: formData.password,
        email: formData.email,
        phone: formData.phone,
        role_ids: formData.role_ids
      })
      MessagePlugin.success('创建成功')
    }
    showCreateDialog.value = false
    loadUsers()
  } catch (error) {
    MessagePlugin.error(editUser.value ? '更新失败' : '创建失败')
  }
}

const handlePasswordSubmit = async () => {
  if (!currentPasswordUser.value) return
  
  try {
    await userAPI.changePassword(currentPasswordUser.value.id, passwordForm.newPassword)
    MessagePlugin.success('密码修改成功')
    showPasswordDialog.value = false
  } catch (error) {
    MessagePlugin.error('密码修改失败')
  }
}

onMounted(() => {
  loadUsers()
  loadRoles()
})
</script>